package servlet;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import dao.QuestionDao;
import entity.QuestionInfo;
import util.DealStrUtil;

public class AddNewQusServlet extends HttpServlet {
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {

		String filename = null;
		String imagePath = null;
		String questionContent = null;
		String explain = null;
		List<String> labels = new ArrayList<String>();
		String optionA = null;
		String optionB = null;
		String optionC = null;
		String optionD = null;
		List<String> answerStrs = new ArrayList<String>();
		
		String qtype = null;
		String qsubject = null;

		try {
			DiskFileItemFactory factory = new DiskFileItemFactory();
			ServletFileUpload upload = new ServletFileUpload(factory);
			// 设置上传文件的大小限制为1M
			factory.setSizeThreshold(1024 * 1024);

			List items = null;
			try {
				items = upload.parseRequest(request);
			} catch (FileUploadException e) {
				e.printStackTrace();
			}

			Iterator iter = items.iterator();
			while (iter.hasNext()) {
				FileItem item = (FileItem) iter.next();
				// 如果提交的是文件
				if (!item.isFormField()) {

					// 根据时间戳创建头像文件
					filename = System.currentTimeMillis() + ".jpg";
					String photoFolder =request.getServletContext().getRealPath("/static/img");
					System.out.println(photoFolder);
					File f = new File(photoFolder, filename);
					f.getParentFile().mkdirs();

					// 获取该图片绝对路径
					//imagePath = f.getAbsolutePath();
					//图片存在实际路径，数据库里保存的图片路径为虚拟路径，在server.xml里配置
					imagePath = "/uploaded/" + filename;
					System.out.println(imagePath);
					

					// 通过item.getInputStream()获取浏览器上传的文件的输入流
					InputStream is = item.getInputStream();

					// 复制文件
					FileOutputStream fos = new FileOutputStream(f);
					byte b[] = new byte[1024 * 1024];
					int length = 0;
					while (-1 != (length = is.read(b))) {
						fos.write(b, 0, length);
					}
					fos.close();

				} else {
					// 常规字段
					if (item.getFieldName().equals("questionContent")) {
						questionContent = new String(item.getString().getBytes("ISO-8859-1"), "UTF-8");
					} else if (item.getFieldName().equals("explain")) {
						explain = new String(item.getString().getBytes("ISO-8859-1"), "UTF-8");
					} else if (item.getFieldName().equals("label")) {
						//此处得改进为数组
						labels.add(new String(item.getString().getBytes("ISO-8859-1"), "UTF-8"));	
					} else if (item.getFieldName().equals("qtype")) {
						qtype = new String(item.getString().getBytes("ISO-8859-1"), "UTF-8");
					} else if (item.getFieldName().equals("qsubject")) {
						qsubject = new String(item.getString().getBytes("ISO-8859-1"), "UTF-8");
					} else if (item.getFieldName().equals("optionA")) {
						optionA = new String(item.getString().getBytes("ISO-8859-1"), "UTF-8");
					} else if (item.getFieldName().equals("optionB")) {
						optionB = new String(item.getString().getBytes("ISO-8859-1"), "UTF-8");
					} else if (item.getFieldName().equals("optionC")) {
						optionC = new String(item.getString().getBytes("ISO-8859-1"), "UTF-8");
					} else if (item.getFieldName().equals("optionD")) {
						optionD = new String(item.getString().getBytes("ISO-8859-1"), "UTF-8");
					} else if (item.getFieldName().equals("correctAnswer")) {
						//此处得改进为数组
						answerStrs.add(new String(item.getString().getBytes("ISO-8859-1"), "UTF-8")); 
					}

				}
			}

		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		QuestionInfo question = new QuestionInfo();
		question.setQuestionContent(questionContent);
		question.setExplain(explain);
		question.setImgUrl(imagePath);
		question.setQtype(Integer.parseInt(qtype));
		question.setQsubject(Integer.parseInt(qsubject));
		String label = new DealStrUtil().transListToStr(labels);
		question.setLabel(label);


		new QuestionDao().addQus(question);
		int questionId = new QuestionDao().getExisQus();
		if ((Integer.parseInt(qtype) == 1) || (Integer.parseInt(qtype) == 2)) {
			new QuestionDao().addOpt(questionId, "A", optionA);
			new QuestionDao().addOpt(questionId, "B", optionB);
			new QuestionDao().addOpt(questionId, "C", optionC);
			new QuestionDao().addOpt(questionId, "D", optionD);
		} else if (Integer.parseInt(qtype) == 3) {
			new QuestionDao().addOpt(questionId, "A", optionA);
			new QuestionDao().addOpt(questionId, "B", optionB);
		}
		// 如果是多选题，该怎么办？
		for (int i = 0; i < answerStrs.size(); i++) {
			new QuestionDao().updateCorrect(questionId, answerStrs.get(i));
			
		}
		
		response.sendRedirect("./questionManage");
	}

}
